
using Identity.Extensions;
using Identity.Interface;
using Identity.Models;

namespace Identity.Service;
public class AdminService(IUser user, INavigation navigations) : IAdminService
{
    private IUser User { get; set; } = user;

    private INavigation Navigations { get; set; } = navigations;

    public bool AuthorizingBlock(string userName, string url, string blockName)
    {
        var ret = User.GetRoles(userName).Any(i => i.Equals("Administrator", StringComparison.OrdinalIgnoreCase));
        if (!ret)
        {
            var menus = Navigations.GetAllMenus(userName);
            var menu = menus.FirstOrDefault(m => m.Url.Contains(url, StringComparison.OrdinalIgnoreCase));
            if (menu != null)
            {
                ret = menus.Any(m => m.ParentId == menu.Id && m.IsResource == EnumResource.Block && m.Url.Equals(blockName, StringComparison.OrdinalIgnoreCase));
            }
        }
        return ret;
    }


  public bool AuthorizingBlock(string userName, string blockName)
    {
        var ret = User.GetRoles(userName).Any(i => i.Equals("Administrator", StringComparison.OrdinalIgnoreCase));
        if (!ret)
        {
            var menus = Navigations.GetAllMenus(userName);
            var menu = menus.Where(m => m.IsResource==EnumResource.Block  && m.Name==blockName).Select(cm=>cm.Name);
            if (menu != null)
            {
                ret = menus.Any(m => menu.Contains(m.Name));
            }
        }
        return ret;
    }


    public Task<bool> AuthorizingNavigation(string userName, string url)
    {
        var ret = Navigations.GetAllMenus(userName).Any(m => m.Url.Contains(url, StringComparison.OrdinalIgnoreCase));
        return Task.FromResult(ret);
    }

    /// <summary>
    /// 通过用户名获取角色集合方法
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    public List<string> GetRoles(string userName) => User.GetRoles(userName);

    /// <summary>
    /// 通过用户名获取授权 App 集合方法
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns> 

 

    public List<string> GetApps(string userName) => User.GetRoles(userName);

    public bool GetMenusByUsernaem(string? userName, string menu, string appid)
    {
        return Navigations.GetMenusByUsernaem (userName,menu,appid);
    }
}